package com.jkoss.wine.warehouse.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.UuidUtil;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.config.mvc.MoneyExcelHandler;
import com.jkoss.wine.merchant.entity.MerchantProductNorm;
import com.jkoss.wine.merchant.service.IMerchantProductNormService;
import com.jkoss.wine.system.service.IMerchantEmployeesService;
import com.jkoss.wine.warehouse.entity.WareInOrder;
import com.jkoss.wine.warehouse.entity.WareInOrderDetails;
import com.jkoss.wine.warehouse.entity.Warehouse;
import com.jkoss.wine.warehouse.service.IWareInOrderDetailsService;
import com.jkoss.wine.warehouse.service.IWareInOrderService;
import com.jkoss.wine.warehouse.service.IWarehouseService;
import com.jkoss.wine.warehouse.vo.WareInOrderExcel;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;

/**
 * 入库单 前端控制器
 * 
 * @Author Jason
 * @Version 1.0, 2018-10-21
 * @See
 * @Since com.jkoss.wine.warehouse.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/warehouse/wareInOrder")
public class WareInOrderController extends BaseController {

	@Autowired
	private IWareInOrderService iWareInOrderService;
	@Autowired
	private IWarehouseService iWarehouseService;
	@Autowired
	private IWareInOrderDetailsService iWareInOrderDetailsService;
	@Autowired
	private IMerchantProductNormService iMerchantProductNormService;
	@Autowired
	private IMerchantEmployeesService iMerchantEmployeesService;

	/**
	 * 列表
	 * 
	 * @param dwzPageBean
	 * @param map
	 * @param onum
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/list")
	@RequiresPermissions("/warehouse/wareInOrder/list")
	public String list(DwzPageBean dwzPageBean, ModelMap map, String onum, HttpServletRequest request, HttpServletResponse response) {
		String inoutonum = request.getParameter("org2.onum");
		Wrapper wrapper = Condition.create().ne("wio.del", 1).like("wio.onum", inoutonum);
		dwzPageBean.getCountResultMap().put("onum", inoutonum);
		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("wio.add_time", false);
		}
		Page resultPage = iWareInOrderService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "warehouse/wareInOrder/list";
	}

	/**
	 * 去新增
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toInsert")
	@RequiresPermissions("/warehouse/wareInOrder/toInsert")
	public String toInsert(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Wrapper whwrapper = Condition.create().ne("del", 1);
		List<Warehouse> warehouses = iWarehouseService.selectList(whwrapper);
		Wrapper mpnwrapper = Condition.create().ne("del", 1);
		map.put("productNorms", iMerchantProductNormService.selectList(mpnwrapper));
		map.put("warehouses", warehouses);
		return "warehouse/wareInOrder/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/warehouse/wareInOrder/toInsert")
	@ResponseBody
	public Object insert(@Valid WareInOrder inout_order, Double opcsPice, String whid[], String pnid[], String amut[], String unpr[], String ttpr[], HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (CommonUtil.isBlank(whid)) {
			return ajaxError("请选择仓库");
		}
		if (CommonUtil.isBlank(pnid)) {
			return ajaxError("请选择商品");
		}
		if (CommonUtil.isBlank(amut)) {
			return ajaxError("请选择数量");
		}

		for (int i = 0; i < pnid.length; i++) {
			if (CommonUtil.isBlank(pnid[i])) {
				return ajaxError("第" + (i + 1) + "行，商品不能为空");
			} else if (CommonUtil.isBlank(whid[i])) {
				return ajaxError("第" + (i + 1) + "行，仓库不能为空");
			} else if (CommonUtil.isBlank(amut[i])) {
				return ajaxError("第" + (i + 1) + "行，数量不能为空");
			} else if (CommonUtil.isBlank(unpr[i])) {
				return ajaxError("第" + (i + 1) + "行，单价不能为空");
			} else if (CommonUtil.isBlank(ttpr[i])) {
				return ajaxError("第" + (i + 1) + "行，总价不能为空");
			}
		}
		// 判断订单编号是否存在
		Wrapper wrapper = Condition.create().ne("del", 1).eq("onum", inout_order.getOnum());
		WareInOrder wareInoutOrderExist = iWareInOrderService.selectOne(wrapper);
		if (!CommonUtil.isBlank(wareInoutOrderExist) && wareInoutOrderExist.getDel() != 1) {
			return ajaxError("订单编号已存在");
		}
		// 制单人
		inout_order.setSgps(getUserId());
		// 添加时间
		inout_order.setAddTime(CommonUtil.getDate());
		// 操作人
		inout_order.setOperator(getUserId());
		// 是否删除 0否 1是
		inout_order.setDel(0);
		// 订单类型：1-出库、2-入库
		inout_order.setType(2);
		inout_order.setOpcs(BigDecimal.valueOf(opcsPice).multiply(BigDecimal.valueOf(100)).intValue());
		if (iWareInOrderService.insertInOrder(inout_order, whid, pnid, amut, unpr, ttpr)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去修改
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUpdate")
	@RequiresPermissions("/warehouse/wareInOrder/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		map.put("record", iWareInOrderService.selectById(id));
		Wrapper wrapper = Condition.create().eq("wood.ioid", id).ne("wood.del", 1);
		map.put("orderDetails", iWareInOrderDetailsService.selectVoByIoid(wrapper));
		Wrapper whwrapper = Condition.create().ne("del", 1);
		List<Warehouse> warehouses = iWarehouseService.selectList(whwrapper);
		Wrapper mpnwrapper = Condition.create().ne("del", 1);
		map.put("productNorms", iMerchantProductNormService.selectList(mpnwrapper));
		map.put("warehouses", warehouses);
		return "warehouse/wareInOrder/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/warehouse/wareInOrder/toUpdate")
	@ResponseBody
	public Object update(@Valid WareInOrder inout_order, Double opcsPice, String wioodid[], String whid[], String pnid[], String amut[], String unpr[], String ttpr[], HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (CommonUtil.isBlank(whid)) {
			return ajaxError("请选择仓库");
		}
		if (CommonUtil.isBlank(pnid)) {
			return ajaxError("请选择商品");
		}
		if (CommonUtil.isBlank(amut)) {
			return ajaxError("请选择数量");
		}
		if (CommonUtil.isBlank(unpr)) {
			return ajaxError("请填写单价");
		}
		if (CommonUtil.isBlank(ttpr)) {
			return ajaxError("请填写总价");
		}

		for (int i = 0; i < whid.length; i++) {
			if (CommonUtil.isBlank(pnid[i])) {
				return ajaxError("第" + (i + 1) + "行，商品不能为空");
			} else if (CommonUtil.isBlank(whid[i])) {
				return ajaxError("第" + (i + 1) + "行，仓库不能为空");
			} else if (CommonUtil.isBlank(amut[i])) {
				return ajaxError("第" + (i + 1) + "行，数量不能为空");
			} else if (CommonUtil.isBlank(unpr[i])) {
				return ajaxError("第" + (i + 1) + "行，单价不能为空");
			} else if (CommonUtil.isBlank(ttpr[i])) {
				return ajaxError("第" + (i + 1) + "行，总价不能为空");
			}
		}

		// 判断订单编号是否存在
		Wrapper wrapper = Condition.create().ne("del", 1).eq("onum", inout_order.getOnum()).ne("id", inout_order.getId());
		WareInOrder wareInoutOrderExist = iWareInOrderService.selectOne(wrapper);
		if (!CommonUtil.isBlank(wareInoutOrderExist)) {
			return ajaxError("订单编号已存在");
		}
		inout_order.setOpcs(BigDecimal.valueOf(opcsPice).multiply(BigDecimal.valueOf(100)).intValue());
		if (iWareInOrderService.updateInOrder(inout_order, wioodid, whid, pnid, amut, unpr, ttpr)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去删除
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("/warehouse/wareInOrder/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<WareInOrder> list = new ArrayList();
		for (String string : id) {
			WareInOrder inoutOrder = new WareInOrder();
			inoutOrder.setId(string);
			// 是否删除：0-未删除、1-已删除、2-不能删除
			inoutOrder.setDel(1);
			list.add(inoutOrder);
		}
		if (iWareInOrderService.deleteInoutOrder(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 查询订单编号
	 * 
	 * @param orderNum
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/getInonum")
	@ResponseBody
	public Object getInonum(String onum, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Wrapper wrapper = Condition.create().like("onum", onum).ne("del", 1).eq("type", 2);
		List<WareInOrder> list = iWareInOrderService.selectList(wrapper);
		return JSON.toJSONString(list);
	}

	/**
	 * 导出EXCEL
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/export")
	@RequiresPermissions("/warehouse/wareInOrder/export")
	public String export(ModelMap map, DwzPageBean dwzPageBean, HttpServletRequest request, HttpServletResponse response) {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().ne("wio.del", 1).orderBy("wio.id", true);
		// 根据用户id获取角色
		// boolean isDirector = true;
		// List<Role> roles = getRoleList();
		// for (Role role : roles) {
		// if ("运营主管".equals(role.getName())) {
		// isDirector = false;
		// }
		// }
		// if (isDirector) {
		// wrapper.eq("maid", getUserId());
		// }
		Page page = dwzPageBean.toPage();
		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		List list = iWareInOrderService.selectVoExcel(page, wrapper).getRecords();
		ExportParams params = new ExportParams(null, "入库单", ExcelType.XSSF);
		IExcelDataHandler dataHandler = new MoneyExcelHandler();
		dataHandler.setNeedHandlerFields(new String[] { "订单金额", "入库单价", "入库总价" });
		params.setDataHandler(dataHandler);
		map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
		map.put(NormalExcelConstants.CLASS, WareInOrderExcel.class);// 导出实体
		map.put(NormalExcelConstants.PARAMS, params);// 参数
		map.put(NormalExcelConstants.FILE_NAME, "入库单");// 文件名称
		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;// View名称

	}

	/**
	 * 去导入页面
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toImportExcel")
	@RequiresPermissions("/warehouse/wareInOrder/toImportExcel")
	public String toImportExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		return "/warehouse/wareInOrder/importExcel";
	}

	/**
	 * 导入EXCEL
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/importExcel")
	@RequiresPermissions("/warehouse/wareInOrder/toImportExcel")
	@ResponseBody
	public Object importExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 1.构造导入参数
		ImportParams params = new ImportParams();
		IExcelDataHandler dataHandler = new MoneyExcelHandler();
		dataHandler.setNeedHandlerFields(new String[] { "订单金额", "入库单价", "入库总价" });
		params.setDataHandler(dataHandler);
		// 指定title位置
		// 2.importExcelMore解释Excel
		ExcelImportResult<WareInOrderExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), WareInOrderExcel.class, params);
		// 3.插入数据库
		List<WareInOrderExcel> wareInOrderExcels = result.getList();
		if (!CommonUtil.isBlank(wareInOrderExcels)) {
			// 为提高效率一次查询所有用户，放到map当中
			Map<String, String> whmap = new HashMap();
			List<Warehouse> warehouses = iWarehouseService.selectList(null);
			if (!CommonUtil.isBlank(warehouses)) {
				for (Warehouse warehouse : warehouses) {
					whmap.put(warehouse.getName(), warehouse.getId());
				}
			}
			// 为提高效率一次查询所有用户，放到map当中
			Map<String, String> mpnmap = new HashMap();
			List<MerchantProductNorm> merchantProductNorms = iMerchantProductNormService.selectList(null);
			if (!CommonUtil.isBlank(merchantProductNorms)) {
				for (MerchantProductNorm merchantProductNorm : merchantProductNorms) {
					mpnmap.put(merchantProductNorm.getNormName(), merchantProductNorm.getMerchantProductNormId());
				}
			}

			List<WareInOrder> wareInOrders = new ArrayList();
			List<WareInOrderDetails> wareInOrderDetails = new ArrayList();
			Map map = new HashMap();

			for (WareInOrderExcel wareInOrderExcel : wareInOrderExcels) {
				// 把wareInOrderExcel转换成WareInOrder
				WareInOrder wareInOrder = CommonUtil.cloneJavaBean(wareInOrderExcel, WareInOrder.class);
				if (CommonUtil.isBlank(map.get(wareInOrder.getOnum()))) {
					map.put(wareInOrder.getOnum(), wareInOrder.getOnum());
					wareInOrder.setId(UuidUtil.getUUID());
					// 制单人
					wareInOrder.setSgps(getUserId());
					// 操作人
					wareInOrder.setOperator(getUserId());
					// 添加时间
					wareInOrder.setAddTime(CommonUtil.getDate());
					// 是否删除：0-未删除、1-已删除、2-不能删除
					wareInOrder.setDel(0);
					wareInOrders.add(wareInOrder);
				}

				// 把wareInOrderExcel转换成WareInOrder
				WareInOrderDetails wareInOrderDetails2 = new WareInOrderDetails();
				// 操作人
				wareInOrderDetails2.setOperator(getUserId());
				// 添加时间
				wareInOrderDetails2.setAddTime(CommonUtil.getDate());
				// 是否删除：0-未删除、1-已删除、2-不能删除
				wareInOrderDetails2.setDel(0);
				// 订单id
				wareInOrderDetails2.setIoid(wareInOrder.getId());
				// 商品规格id
				wareInOrderDetails2.setPnid(mpnmap.get(wareInOrderExcel.getPnname()));
				// 仓库id
				wareInOrderDetails2.setWhid(whmap.get(wareInOrderExcel.getWhname()));
				// 数量
				wareInOrderDetails2.setAmut(wareInOrderExcel.getAmut());
				// 单价
				wareInOrderDetails2.setUnpr(wareInOrderExcel.getUnpr());
				// 总价
				wareInOrderDetails2.setTtpr(wareInOrderExcel.getTtpr());

				wareInOrderDetails.add(wareInOrderDetails2);

			}
			if (!iWareInOrderService.insertBatch(wareInOrders)) {
				return ajaxError("添加数据失败！");
			}
			if (!iWareInOrderDetailsService.insertBatch(wareInOrderDetails)) {
				return ajaxError("添加数据失败！");
			}
		} else {
			return ajaxError("数据内容为空！");
		}
		return ajaxSuccess();
	}

	/**
	 * 订单详情
	 * 
	 * @param dwzPageBean
	 * @param wname
	 * @param ioid
	 * @param map
	 * @param str
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/details")
	@RequiresPermissions("/warehouse/wareInOrder/details")
	public String details(DwzPageBean dwzPageBean, String wname, String ioid, ModelMap map, String str, HttpServletRequest request, HttpServletResponse response) {
		map.put("str", str);
		map.put("ioid", ioid);
		map.put("details", iWareInOrderService.selectVoById(ioid));
		Wrapper wrapper = Condition.create().eq("io.id", ioid).ne("od.del", 1);
		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("od.add_time", false);
		}
		Page resultPage = iWareInOrderService.selectVoByioid(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "warehouse/wareInOrder/details";
	}
}
